package com.jml.类加载器.热部署;

import org.junit.Test;

import java.io.File;
import java.lang.reflect.Method;

public class Hotswap {

    //"D:\jml-work\code\ideaProject\constructor\jvm\target\classes\com\jml\类加载器\热部署"
    @Test
    public void main001() throws InterruptedException {
        User user1 = new User();
        user1.add();
        System.out.println("====================");
        //将user2.0版本的文件来替代user1.0版本的文件
        //第二次运行这个类如果存在User.class文件，就不会再编译user.java
        Thread.sleep(15*1000);
        User user2 = new User();
        user2.add();
    }



    public static void main(String[] args) throws Exception {
        //加载项目中的类class
        loadUser();
        System.gc();
        Thread.sleep(1000);// 等待资源回收
        // 需要被热部署的class文件
        File file1 = new File("C:\\Users\\jml94\\Desktop\\User.class");
        // 之前编译好的class文件
        File file2 = new File(
                "D:\\jml-work\\code\\ideaProject\\constructor\\jvm\\target\\classes\\com\\jml\\类加载器\\热部署\\User.class");
        boolean isDelete = file2.delete();// 删除旧版本的class文件
        if (!isDelete) {
            System.out.println("热部署失败.");
            return;
        }
        //将项目外的类替换到项目中class
        file1.renameTo(file2);
        System.out.println("update success!");
        //再次加载替换后的
        loadUser();
    }



    public static void loadUser() throws  Exception {
        MyClassLoader myLoader = new MyClassLoader();
        //类加载器读取信息
        Class<?> class1 = myLoader.findClass("com.jml.类加载器.热部署.User");
        Object obj1 = class1.newInstance();
        Method method = class1.getMethod("add");
        method.invoke(obj1);
        System.out.println(obj1.getClass());
        System.out.println(obj1.getClass().getClassLoader());
    }









}
